import { Component } from '@angular/core';
import { ICellRendererAngularComp } from '@ag-grid-community/angular';
import { AllModules, Module } from '@ag-grid-enterprise/all-modules';
import { GridOptions } from '@ag-grid-community/core';
import { RenderOperatingButtonComponent } from '@shared/ag-grid-ext/cell-renders/render-operating-button.component';
import { GridConfigService } from '@core/config/grid-config.service';
import { ExpressionService } from '@core/services/expression/ExpressionService';


@Component({
  selector: 'apes-render-custom-detail',
  template: `
    <div class="apes-custom-detail">
      <apes-descriptions apesBordered="{{bordered}}" [apesSize]="'small'" [apesColumn]="column">
        <ng-container *ngFor="let col of colDefs">
          <apes-descriptions-item *ngIf="!getHide(col)"
                                  [apesTitle]="col.headerName?col.headerName : null"
                                  [apesSpan]="span">
            <div>{{formatter(rowData, col.field, getValueFormatter(col))}}</div>
          </apes-descriptions-item>
        </ng-container>
      </apes-descriptions>
    </div>
  `,
  styles: [`
    .apes-custom-detail {
      padding: 8px;
    }

  `],
})
export class RenderCustomDetailComponent implements ICellRendererAngularComp {
  refresh(params: any): boolean {
    return false;
  }

  params: any;
  rowData: any[] = [];
  colDefs: any;
  bordered: boolean = false;
  ctx: any = {};
  column: number = 4;
  span:number = 1;

  constructor(
    private gridConfigService: GridConfigService,
    private  expressionService: ExpressionService,
  ) {
  }

  agInit(params: any): void {

    this.params = params;
    this.colDefs = params.detailGridOptions.columnDefs;
    if(params.detailGridOptions.options){
      let options = params.detailGridOptions.options
      this.column = options['column'] ? options['column'] : 4;
      this.span = options['span'] ? options['span'] : 1;
    }
    this.rowData = params.data;
    if (params.context) {
      this.ctx = params.context;
    }
  }

  getValueFormatter(data): string {
    return data.valueFormatter || 'value';
  }

  getHide(data) {
    let expression = data.hideExpression || 'false';
    return this.expressionService.evaluate(expression, {
      context: this.ctx,
      model: this.ctx['model'],
      data: this.rowData,
    });
  }

  formatter(data: any, key: any, expression: string) {
    return this.expressionService.evaluate(expression, {
      value: data[key],
    });
  }

}
